﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.ModelBinding;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace Magicodes.WeiChat.Infrastructure.MvcExtension.ModelBinder
{
    /// <summary>
    /// XML Model绑定
    /// Demo:public ActionResult PostXmlContent([ModelBinder(typeof(XmlModelBinder))]UserViewModel user)
    /// </summary>
    public class XmlModelBinder : System.Web.Mvc.IModelBinder
    {
        
        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            try
            {
                var modelType = bindingContext.ModelType;
                var serializer = new XmlSerializer(modelType);
                var inputStream = controllerContext.HttpContext.Request.InputStream;
                return serializer.Deserialize(inputStream);
            }
            catch
            {
                bindingContext.ModelState.AddModelError("", "该项无法被序列化！");
                return null;
            }
        }
    }
}
